
from ...service.mongo_bill_service import MongoBillFilter
from server.pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
from ...service.buss_pub.bill_manage import BillManageService, OperationType, TypeId, Status
from ...service.common import insert_data, find_data, update_data, delete_data, get_condition, get_info
from ...pao_python.pao.service.security.security_utility import get_current_account_id
from ...pao_python.pao.service.security.security_service import RoleService
import hashlib
import re
import datetime
import uuid
import pandas as pd
from ...pao_python.pao.data import process_db, dataframe_to_list, DataProcess, DataList
'''
@Description: In User Settings Edit
@Author: your name
@Date: 2019-07-25 18:32:31
@LastEditTime: 2019-07-25 18:32:31
@LastEditors: your name
'''
# -*- coding: utf-8 -*-

'''
服务项目函数
'''


class ServicesProjectService(MongoService):
    ''' 服务项目 '''

    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        DataProcess.__init__(self, db_addr, db_port, db_name, db_user, db_pwd,)
        # self.db_name = db_name
        self.inital_password = inital_password
        self.session = session
        self.role_service = RoleService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)
        self.bill_manage_service = BillManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)

    def get_services_project_list(self, org_list, condition, page=None, count=None):
        '''获取服务项目列表

        Arguments:
            condition   {dict}      条件
            page        {number}    页码
            count       {number}    条数
        '''
        keys = ['id', 'name', 'item_type_id',
                'is_standard_service', 'organization_name']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.lookup_bill('PT_User', 'organization_id', 'id', 'organ')\
            .lookup_bill('PT_Services_Item_Category', 'item_type', 'id', 'itemType')\
            .add_fields({
                'organization_name': '$organ.name',
                'type_name': '$itemType.name',
                # 'scope_name':'$scope.name'
            })\
            .match_bill((C('item_type') == values['item_type_id']) &
                        (C('id') == values['id']) & (C('is_standard_service') == values['is_standard_service']) &
                        (C('organization_name').like(values['organization_name'])) &
                        (C('name').like(values['name'])) &
                        (C('organization_id').inner(org_list)))\
            .project({'_id': 0, 'organ._id': 0, 'itemType._id': 0})
        if 'id' in list(condition.keys()):
            _filter.lookup_bill('PT_Service_Option', 'service_option.option_name', 'id', 'service_options')\
                   .project({'_id': 0, 'service_options._id': 0})
        res = self.page_query(
            _filter, 'PT_Service_Item', page, count)
        return res

    def get_services_project_list2(self, condition, page, count):
        '''获取服务项目列表

        Arguments:
            condition   {dict}      条件
            page        {number}    页码
            count       {number}    条数
        '''
        keys = ['id', 'item_type_id',
                'is_standard_service', 'organization_name']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.lookup_bill('PT_User', 'organization', 'id', 'organ')\
            .lookup_bill('PT_Services_Item_Category', 'item_type', 'id', 'itemType')\
            .add_fields({
                'organization_name': '$organ.name',
                'type_name': '$itemType.name',
                # 'scope_name':'$scope.name'
            })\
            .match_bill((C('item_type') == values['item_type_id']) & (C('id') == values['id']) & (C('is_standard_service') == values['is_standard_service']) & (C('organization_name').like(values['organization_name'])))\
            .project({'_id': 0, 'organ._id': 0, 'itemType._id': 0})
        # if 'id' in list(condition.keys()):
        #     _filter.lookup_bill('PT_Service_Option', 'service_option.option_name', 'id', 'service_options')\
        #            .project({'_id': 0, 'service_options._id': 0})
        res = self.page_query(
            _filter, 'PT_Service_Item', page, count)

        # 存在数据库的是name和id，但是前端需要option_name和option_id，所以需要在接口做转换
        for index in range(len(res['result'][0]['service_option'])):
            temp = res['result'][0]['service_option'][index]
            if 'name' in temp:
                res['result'][0]['service_option'][index]['option_name'] = temp['name']
                del(res['result'][0]['service_option'][index]['name'])
            if 'id' in temp:
                res['result'][0]['service_option'][index]['option_id'] = temp['id']
                del(res['result'][0]['service_option'][index]['id'])

        return res

    def get_all_item_from_product(self, condition):
        '''获取所有服务产品下所有的服务项目'''
        keys = ['id']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()\
            .match_bill(C('id') == values['id'])\
            .project({'_id': 0})
        root = self.page_query(_filter, 'PT_Service_Product', 1, 1)
        if len(root['result']):
            root_product = root['result'][0]
            reslut = []
            self.__iter_get_item(root_product, reslut)
            res = {'result': reslut, 'total': len(reslut)}
            return res

    def __iter_get_item(self, root_product, result):
        '''遍历出所有服务项目item'''
        if 'is_service_item' in root_product.keys():
            if root_product['is_service_item'] == 'false':
                print('---------', root_product)
                for product in root_product['service_product']:
                    _filter = MongoBillFilter()\
                        .match_bill(C('id') == product['product_id'])\
                        .project({'_id': 0})
                    print('---------', product['product_id'])
                    res = self.page_query(_filter, 'PT_Service_Product', 1, 1)
                    if len(res['result']):
                        self.__iter_get_item(res['result'][0], result)
            elif root_product['is_service_item'] == 'true':
                res = self.get_services_project_list(
                    N(), {'id': root_product['service_item_id']})
                if len(res['result']) > 0:
                    res['result'][0]['product_id'] = root_product['id']
                    res['result'][0]['product_name'] = root_product['name']
                    res['result'][0]['valuation_formula'] = root_product['valuation_formula']
                    res['result'][0]['contract_terms'] = root_product['additonal_contract_terms']
                    res['result'][0]['service_option'] = root_product['service_option']
                    result.append(res['result'][0])

    def update_services_project(self, services_project):
        '''# 新增/修改服务项目'''
        res = 'Fail'

        def process_func(db):
            nonlocal res
            if 'id' in services_project.keys():
                bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
                                                            TypeId.servicesProject.value, services_project, 'PT_Service_Item')
                if bill_id:
                    res = 'Success'
            else:
                bill_id = self.bill_manage_service.add_bill(OperationType.add.value,
                                                            TypeId.servicesProject.value, services_project, 'PT_Service_Item')
                if bill_id:
                    res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def delete_services_project(self, services_project_ids):
        '''删除服务项目接口

        Arguments:
            services_project_ids   {ids}      数据id
        '''
        res = 'fail'

        def process_func(db):
            nonlocal res
            ids = []
            if isinstance(services_project_ids, str):
                ids.append(services_project_ids)
            else:
                ids = services_project_ids
            for services_project_id in ids:
                # 查询被删除的数据信息
                data = find_data(db, 'PT_Service_Item', {
                    'id': services_project_id, 'bill_status': Status.bill_valid.value})
                if len(data) > 0:
                    self.bill_manage_service.add_bill(OperationType.delete.value,
                                                      TypeId.servicesProject.value, data[0], 'PT_Service_Item')
            res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def get_services_periodicity_list(self, condition, page, count):
        '''获取服务周期列表

        Arguments:
            condition   {dict}      条件
            page        {number}    页码
            count       {number}    条数
        '''
        keys = ['id']
        values = self.get_value(condition, keys)
        _filter = MongoFilter()
        _filter.match((C('id') == values['id']))\
            .project({'_id': 0, })
        res = self.page_query(
            _filter, 'PT_Periodicity_Date', page, count)
        return res
